<template>
  <div>
    <el-empty v-if="!sessionId" description="无聊天"></el-empty>
    <el-card v-else class="box-card" body-style="padding:0">
      <div class="header-title">
        <span>{{ title }}</span>
        <el-button style="float: right; padding: 3px 0" type="text"
          >操作按钮</el-button
        >
      </div>
      <div class="content">
        <virtual-list
          v-show="!!messges.length"
          class="content-scroll"
          :class="{ overflow: overflow }"
          ref="vsl"
          :data-key="'messageId'"
          :data-sources="messges"
          :data-component="messageComponent"
          :estimate-size="50"
          :item-class="'stream-item'"
          @resized="onItemRendered"
          @totop="onTotop"
          @scroll="() => (bottom = false)"
          @tobottom="() => (bottom = true)"
        >
          <div slot="header" v-show="overflow" class="header">
            <div class="spinner" v-show="!finished"></div>
            <div class="finished" v-show="finished">没有更多了</div>
          </div>
        </virtual-list>
      </div>
      <div class="input-content">
        <div class="input-content-tools">
          <i class="icon-tools el-icon-edit"></i>
          <i class="icon-tools el-icon-share"></i>
          <i class="icon-tools el-icon-delete"></i>
        </div>
        <el-input
          :rows="3"
          type="textarea"
          placeholder="想聊点什么"
          v-model="messageText"
          maxlength="100"
          resize="none"
          @focus="onMessageFocus"
        >
        </el-input>
        <el-button size="mini" @click="sendMessage" :loading="sendBtLoading"
          >发送</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script>
import Message from "@/components/Message";
import VirtualList from "vue-virtual-scroll-list";
import { MessageUserRecords, ChatSession } from "@/api/api";
export default {
  data() {
    return {
      sessionId: "",
      session: {},
      messageText: "",
      messageComponent: Message,
      overflow: true,
      bottom: false,
      finished: false,
      sendBtLoading: false,
      param: {
        messageId: "",
        pageSize: 15,
        isFirstPageReady: false,
        isFetching: false,
      },
      messges: [],
    };
  },
  created() {
    this.onLoad(this.$route.query.sessionId);
  },
  computed: {
    title() {
      if (!this.session) {
        return "";
      }

      if (this.session.sessionType === "GROUP") {
        return this.session.groupProfile.groupName;
      }
      return this.session.userProfile.friendMemo;
    },
    // messges() {
    //   if (this.$_.isEmpty(this.sessionId)) {
    //     return [];
    //   }
    //   let result = this.$store.state.MESSAGE_LIST[this.sessionId];
    //   return result ? result : [];
    // },
  },
  watch: {
    // eslint-disable-next-line no-unused-vars
    $route(to, from) {
      //刷新参数放到这里里面去触发就可以刷新相同界面了
      this.onLoad(this.$route.query.sessionId);
    },
  },
  methods: {
    async onLoad(sessionId) {
      this.sessionId = sessionId;
      this.$store.commit("clearMessage", sessionId);
      this.param = {
        messageId: "",
        pageSize: 15,
        isFirstPageReady: false,
        isFetching: false,
      };
      this.session = this.$store.getters.getSession(sessionId);
      if (!this.session && !this.$_.isEmpty(sessionId)) {
        //获取会话
        this.session = await ChatSession.get(sessionId);
        this.$store.commit("addSession", [this.session]);
      }
      this.onTotop();
      this.readCount();
    },
    sendMessage() {
      if (this.$_.isEmpty(this.messageText)) {
        this.$message({
          message: "请输入消息",
          type: "warning",
        });
        return;
      }
      this.sendBtLoading = true;
      let message = this.messageText;
      this.messageText = "";
      MessageUserRecords.createMessage(this.sessionId, "TEXT", {
        text: message,
      })
        .then((res) => {
          this.sendBtLoading = false;
          this.$store.commit("addMessage", res);
          MessageUserRecords.sendMessage(this.sessionId, res.messageId).catch(
            () => {
              this.$store.commit("failMessage", res);
            }
          );
          this.setVirtualListToBottom();
        })
        .catch((err) => {
          console.log(err);
          this.sendBtLoading = false;
        });
    },
    onTotop() {
      if (this.$_.isEmpty(this.sessionId) || this.param.isFetching) {
        return;
      }
      this.param.isFetching = true;
      MessageUserRecords.list(this.sessionId, this.param.messageId)
        .then((res) => {
          if (!res.messages.length) {
            this.finished = true;
            return;
          }
          this.finished = res.finished;
          if (res.messages && res.messages.length > 0) {
            this.param.messageId = res.messages[0].messageId;
          }

          // this.$store.commit("frontMessage", {
          //   sessionId: this.sessionId,
          //   messages: res.messages,
          // });
          var sids = res.messages.map((item) => item.messageId);
          this.messges = res.messages.concat(this.messges);
          if (this.param.isFirstPageReady) {
            this.$nextTick(() => {
              const vsl = this.$refs.vsl;
              const offset = sids.reduce((previousValue, currentSid) => {
                const previousSize =
                  typeof previousValue === "string"
                    ? vsl.getSize(previousValue)
                    : previousValue;
                return previousSize + this.$refs.vsl.getSize(currentSid);
              });
              console.log(offset);
              this.setVirtualListToOffset(offset);
              this.param.isFetching = false;
            });
          } else {
            this.param.isFetching = false;
          }
        })
        .catch((err) => {
          this.param.isFetching = false;
          console.log(err);
        });
    },
    onItemRendered() {
      if (!this.$refs.vsl) {
        return;
      }
      // first page items are all mounted, scroll to bottom
      if (
        !this.param.isFirstPageReady &&
        this.$refs.vsl.getSizes() >= this.param.pageSize
      ) {
        this.param.isFirstPageReady = true;
        this.setVirtualListToBottom();
      }
      if (this.bottom) {
        this.setVirtualListToBottom();
      }
      this.checkOverFlow();
    },
    checkOverFlow() {
      const vsl = this.$refs.vsl;
      if (vsl) {
        this.overflow = vsl.getScrollSize() > vsl.getClientSize();
      }
    },

    setVirtualListToIndex(index) {
      if (this.$refs.vsl) {
        this.$refs.vsl.scrollToIndex(index);
      }
    },

    setVirtualListToOffset(offset) {
      if (this.$refs.vsl) {
        this.$refs.vsl.scrollToOffset(offset);
      }
    },

    setVirtualListToBottom() {
      if (this.$refs.vsl) {
        this.$refs.vsl.scrollToBottom();
      }
    },
    onMessageFocus() {
      if (this.$store.getters.countSessionUnreadMessage(this.sessionId) > 0) {
        this.readCount();
      }
    },
    readCount() {
      if (this.$_.isEmpty(this.sessionId)) {
        return;
      }
      ChatSession.readCount(this.sessionId).then((res) => {
        this.session = res;
        this.$store.commit("coverSession", res);
      });
    },
  },
  components: {
    VirtualList,
  },
};
</script>

<style lang="less">
.el-textarea__inner {
  border: none;
}
.header-title {
  height: 52px;
  border-bottom: 1px solid #ebeef59e;
  box-sizing: border-box;
  padding: 10px 15px;
}
.content {
  height: 426px;
}
.content-scroll {
  position: relative;
  width: 100%;
  height: 426px;
  overflow-y: auto;
  background-color: #ebeef59e;
  display: flex;
  flex-direction: column-reverse;
  @media (max-width: 640px) {
    height: 426px;
  }
  &.overflow {
    flex-direction: column;
  }
  .stream-item {
    display: flex;
    align-items: center;
    padding: 1em;
    @media (max-width: 640px) {
      padding: 0.5em;
    }
    &.creator {
      flex-direction: row-reverse;
    }
  }
}

/*滚动条样式*/
.content-scroll::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 4px;
}
.content-scroll::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 5px #e0e2e6;
  background: rgba(0, 0, 0, 0.2);
}
.content-scroll::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px #fff;
  border-radius: 0;
  background: rgba(0, 0, 0, 0.1);
}

.header {
  padding: 0.5em;
  .finished {
    font-size: 14px;
    text-align: center;
    color: #bfbfbf;
  }
  .spinner {
    font-size: 10px;
    margin: 0px auto;
    text-indent: -9999em;
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background: #ffffff;
    background: linear-gradient(to right, #ccc 10%, rgba(255, 255, 255, 0) 42%);
    position: relative;
    animation: load3 1.4s infinite linear;
    transform: translateZ(0);
  }
  .spinner:before {
    width: 50%;
    height: 50%;
    background: #ccc;
    border-radius: 100% 0 0 0;
    position: absolute;
    top: 0;
    left: 0;
    content: "";
  }
  .spinner:after {
    background: #ffffff;
    width: 75%;
    height: 75%;
    border-radius: 50%;
    content: "";
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
  }
  @-webkit-keyframes load3 {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
  @keyframes load3 {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
}
.input-content {
  height: 140px;
  text-align: right;
}
.input-content-tools {
  height: 40px;
  text-align: left;
  font-size: 20px;
}
.icon-tools {
  margin: 10px 5px;
}
</style>